import json
import logging
import traceback
from datetime import datetime
from django.db import transaction
from django.http import JsonResponse
from rest_framework import status
from Model.models import District as D
from tools.Tools import check_text, getCurrentUser, createHandleLog

logger_info = logging.getLogger('info')
res = dict()


def District(request):
    res.clear()
    try:
        if request.method == 'GET':
            return queryDistrict(request)
        elif request.method == 'POST':
            return createDistrict(request)
        elif request.method == 'PUT':
            return modifyDistrict(request)
        elif request.method == 'DELETE':
            return delDistrict(request)
    except Exception as e:
        print(e)
        logger_info.error(f'当前接口：{request.path} 异常，异常内容为:{traceback.format_exc()}')
        res['status'] = 200
        res['message'] = '请求错误!'
        return JsonResponse(res, status=status.HTTP_400_BAD_REQUEST)


# 获取区域信息
def queryDistrict(request):
    name = request.GET.get('name')
    city = request.GET.get('city')
    district = D.objects.all()
    if check_text(name):
        userInfo = district.objectsfilter(name__contains=name)
    if check_text(city):
        userInfo = district.filter(city__contains=city)
    res['status'] = 200
    res['data'] = list(district.values())
    res['message'] = '请求成功'
    return JsonResponse(res, status=status.HTTP_200_OK)


# 新建区域
@transaction.atomic
def createDistrict(request):
    body = json.loads(request.body)
    name = body.get('name')
    city = body.get('city')
    district = D.objects.create()
    district.district_id = district.id
    district.name = name
    district.city = city
    createHandleLog('新增区域', str(getCurrentUser(request)), body)
    logger_info.info(f'{getCurrentUser(request)} 在 {str(datetime.now())[:19]} 操作《新增区域》权限 新增内容 {body}')
    district.save()
    res['status'] = 200
    res['message'] = '新建成功'
    return JsonResponse(res, status=status.HTTP_200_OK)


# 修改区域
@transaction.atomic
def modifyDistrict(request):
    body = json.loads(request.body)
    district_id = body.get('district_id')
    name = body.get('name')
    city = body.get('city')
    district = D.objects.get(district_id=district_id)
    district.name = name
    district.city = city
    createHandleLog('修改区域', str(getCurrentUser(request)), body)
    logger_info.info(f'{getCurrentUser(request)} 在 {str(datetime.now())[:19]} 操作《修改区域》权限 新增内容 {body}')
    district.save()
    res['status'] = 200
    res['message'] = '修改成功'
    return JsonResponse(res, status=status.HTTP_200_OK)


# 删除用户
@transaction.atomic
def delDistrict(request):
    district_id = request.GET.get('district_id')
    district = D.objects.get(district_id=district_id)
    createHandleLog('删除区域', str(getCurrentUser(request)), district.name)
    logger_info.info(f'{getCurrentUser(request)} 在 {str(datetime.now())[:19]} 操作《删除区域》权限 删除 {district.name}')
    district.delete()
    res['status'] = 200
    res['message'] = '删除成功'
    return JsonResponse(res, status=status.HTTP_200_OK)
